/*
 * Copyright (c) 2021
 * User:LENOVO
 * File:相交链表.java
 * Date:2021/02/18 14:19:18
 */

package org.bytedance.链表和数;

import java.util.HashSet;
import java.util.Set;

/**
 * 编写一个程序，找到两个单链表相交的起始节点。
 */
public class 相交链表 {

    public static void main(String[] args) {
        相交链表 instance = new 相交链表();
        ListNode interSecNode = new ListNode(8);
        ListNode headA = new ListNode(4);
        headA.next = new ListNode(1);
        headA.next.next = interSecNode;
        headA.next.next.next = new ListNode(4);
        headA.next.next.next.next = new ListNode(5);

        ListNode headB = new ListNode(5);
        headB.next = new ListNode(0);
        headB.next.next = new ListNode(1);
        headB.next.next.next = interSecNode;

        ListNode intersectionNode = instance.getIntersectionNode(headA, headB);
        if (intersectionNode != null) {
            System.out.println(intersectionNode.value);
        }
    }

    private static class ListNode {
        int value;
        ListNode next;

        public ListNode(int value) {
            this.value = value;
        }

        public ListNode() {
        }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode ha = headA, hb = headB;
        while (ha != hb) {
            ha = ha.next != null ? ha.next : headB;
            hb = hb.next != null ? hb.next : headA;
        }
        return ha;
    }


}
